package com.exercise;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class Exercise {
    public void start(){
        try{
            List<SocketChannel> allChannel = new ArrayList<>();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(8088));
            Selector selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (true){
                selector.select();
                Set<SelectionKey> keySet = selector.selectedKeys();
                for(SelectionKey key:keySet){
                    if(key.isAcceptable()){
                        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = ssc.accept();
                        if(socketChannel==null) continue;
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector,SelectionKey.OP_READ);
                        allChannel.add(socketChannel);
                        System.out.println(
                                socketChannel.socket().getInetAddress().getHostAddress()+
                                        "上线了，当前在线人数为："+allChannel.size()
                        );
                    }
                    else if(key.isReadable()){
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        buffer.flip();
                        if(buffer.limit()==0){
                            buffer.clear();
                            continue;
                        }
                        byte[] data = new byte[buffer.limit()];
                        buffer.get(data);
                        String message=new String(data, StandardCharsets.UTF_8);
                        message = sc.socket().getInetAddress().getHostAddress()+"说："+message;
                        buffer.clear();
                        for(SocketChannel channel:allChannel){
                            buffer.flip();
                            channel.write(buffer);
                        }
                        buffer.put(message.getBytes(StandardCharsets.UTF_8));
                        System.out.println("客户端说："+message);
                    }
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
